<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
            <el-form-item label="省" prop="provinceId">
                <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                    <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
                <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                    <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="areaId">
                <el-select v-model="queryParams.areaId" placeholder="请选择区/县" @change="chooseArea" clearable>
                    <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="图件分类" prop="mapClassify">
                <el-select v-model="queryParams.mapClassify" placeholder="请选择">
                    <el-option v-for="item in [{ value: '0', label: '基础数据' }, { value: '1', label: '评估结果' }]"
                        :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上传人" prop="uploader">
                <el-input v-model="queryParams.uploader" placeholder="请输入上传人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="上传日期" style="width: 330px">
                <el-date-picker v-model="uploadTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="所属任务" prop="taskName">
                <el-input v-model="queryParams.taskName" placeholder="请输入所属任务" clearable />
            </el-form-item>
            <el-form-item label=" ">
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button plain icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="reportHandleAdd">按简本报告上传</el-button>
                <el-button type="primary" icon="Plus" @click="otherHandleAdd">其他图件上传</el-button>
                <el-button type="primary" @click="chartHandle">一键出图</el-button>
                <el-button type="primary" @click="handleDelete">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="mapId">
            <el-table-column type="selection" width="55" align="center" reserve-selection />
            <el-table-column label="图件名称" align="center" prop="mapName">
                <template #default="scope">
                    <el-button type="text" @click="handleUpdate(scope.row)">{{ scope.row.mapName }}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="图件分类" align="center" prop="mapClassify">
                <template #default="scope">
                    <span>{{ scope.row.mapClassify == '0' ? '基础数据' : '评估结果' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="图件标签" align="center" prop="mapLabel">
                <template #default="{ row }">
                    <span v-if="row.mapLabel == '0'">行政区划图</span>
                    <span v-else-if="row.mapLabel == '1'">人口公里格网分布图</span>
                    <span v-else-if="row.mapLabel == '2'">经济公里格网分布图</span>
                    <span v-else-if="row.mapLabel == '3'">地形图</span>
                    <span v-else-if="row.mapLabel == '4'">地震地质构造图</span>
                    <span v-else-if="row.mapLabel == '5'">交通分布图</span>
                    <span v-else-if="row.mapLabel == '6'">设定地震点分布图</span>
                    <span v-else-if="row.mapLabel == '7'">地质灾害隐患点分布图</span>
                    <span v-else-if="row.mapLabel == '8'">次生危险源分布图</span>
                    <span v-else-if="row.mapLabel == '9'">建筑物综合抗震能力评价图（格网）</span>
                    <span v-else-if="row.mapLabel == '10'">建筑物综合抗震能力评价图（乡镇）</span>
                    <span v-else-if="row.mapLabel == '11'">建筑物综合抗震能力评价图（区县）</span>
                    <span v-else-if="row.mapLabel == '12'">学校分布图</span>
                    <span v-else-if="row.mapLabel == '13'">历史地震分布图</span>
                    <span v-else-if="row.mapLabel == '14'">调研点分布图</span>
                    <span v-else-if="row.mapLabel == '15'">遭遇烈度XX度地震地质灾害风险分布图</span>
                    <span v-else-if="row.mapLabel == '16'">交通遭遇烈度XX度时交通受损情况分布图</span>
                    <span v-else-if="row.mapLabel == '17'">危化企业、加油（加气）站分布图</span>
                    <span v-else-if="row.mapLabel == '18'">水库分布图</span>
                </template>
            </el-table-column>

            <el-table-column label="任务地区" align="center" prop="taskDistrict" />
            <el-table-column label="所属任务" align="center" prop="taskName" />

            <el-table-column label="上传人" align="center" prop="uploader" />
            <el-table-column label="上传日期" align="center" prop="uploadTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 按简本报告上传 -->
        <el-dialog :title="reportTitle" v-model="reportShowPopup" width="800px" append-to-body>
            <el-form ref="reportRef" :model="reportForm" :rules="reportRules" label-width="120px">
                <el-row class="mt15">
                    <el-col :span="12">
                        <el-form-item label="任务名称" prop="taskName">
                            <el-select v-model="reportForm.taskName" filterable @change="chooseTaskName"
                                placeholder="请输入所属任务" :disabled="btnType == 'edit'" style="width: 100%;">
                                <el-option v-for="(item, index) in taskList" :key="item.id"
                                    :label="item.taskCodeAndTaskName" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="图件分类" prop="mapClassify">
                            <el-select v-model="reportForm.mapClassify" placeholder="请选择图件分类" :disabled="btnType == 'edit'"
                                style="width: 100%;">
                                <el-option v-for="item in [{ value: '0', label: '基础数据' }, { value: '1', label: '评估结果' }]"
                                    :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>

                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="图件名称" prop="mapName">
                            <el-input style="width: 100%;" v-model="reportForm.mapName" placeholder="请输入图件名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col v-if="reportForm.mapLabel !== null">
                        <el-form-item label="图件标签" prop="mapLabel">
                            <el-radio-group v-model="reportForm.mapLabel" :disabled="btnType == 'edit'"
                                v-if="!reportForm.mapId">
                                <el-radio label="0">行政区划图</el-radio>
                                <el-radio label="1">人口公里格网分布图</el-radio>
                                <el-radio label="2">经济公里格网分布图</el-radio>
                                <el-radio label="3">地形图</el-radio>
                                <el-radio label="4">地震地质构造图</el-radio>
                                <el-radio label="5">交通分布图</el-radio>
                                <el-radio label="6">设定地震点分布图</el-radio>
                                <el-radio label="7">地质灾害隐患点分布图</el-radio>
                                <el-radio label="8">次生危险源分布图</el-radio>
                            </el-radio-group>
                            <div v-else>
                                <span v-if="reportForm.mapLabel == 0">行政区划图</span>
                                <span v-else-if="reportForm.mapLabel == 1">人口公里格网分布图</span>
                                <span v-else-if="reportForm.mapLabel == 2">经济公里格网分布图</span>
                                <span v-else-if="reportForm.mapLabel == 3">地形图</span>
                                <span v-else-if="reportForm.mapLabel == 4">地震地质构造图</span>
                                <span v-else-if="reportForm.mapLabel == 5">交通分布图</span>
                                <span v-else-if="reportForm.mapLabel == 6">设定地震点分布图</span>
                                <span v-else-if="reportForm.mapLabel == 7">地质灾害隐患点分布图</span>
                                <span v-else-if="reportForm.mapLabel == 8">次生危险源分布图</span>
                                <span v-else-if="reportForm.mapLabel == 9">建筑物综合抗震能力评价图（格网）</span>
                                <span v-else-if="reportForm.mapLabel == 10">建筑物综合抗震能力评价图（乡镇）</span>
                                <span v-else-if="reportForm.mapLabel == 11">建筑物综合抗震能力评价图（区县）</span>
                                <span v-else-if="reportForm.mapLabel == 12">学校分布图</span>
                                <span v-else-if="reportForm.mapLabel == 13">历史地震分布图</span>
                                <span v-else-if="reportForm.mapLabel == 14">调研点分布图</span>
                                <span v-else-if="reportForm.mapLabel == 15">遭遇烈度XX度地震地质灾害风险分布图</span>
                                <span v-else-if="reportForm.mapLabel == 16">交通遭遇烈度XX度时交通受损情况分布图</span>
                                <span v-else-if="reportForm.mapLabel == 17">危化企业、加油（加气）站分布图</span>
                                <span v-else-if="reportForm.mapLabel == 18">水库分布图</span>
                            </div>

                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="图片" prop="picture">
                            <image-upload ref="reportImgUpload" :fileSize="100" :limit="1" downloadUrl="downLoad"
                                v-model="reportForm.attachList" :show-file-list="false" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="图件描述" prop="mapDescription">
                            <el-input v-model="reportForm.mapDescription" type="textarea" maxlength="1000" show-word-limit
                                :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入图件描述" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="uploadImg" v-show="btnType == 'edit'">下载图件</el-button>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button plain @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 其他图件上传 -->
        <el-dialog :title="otherTitle" v-model="otherShowPopup" width="800px" append-to-body>
            <el-form ref="otherRef" :model="otherForm" :rules="otherRules" label-width="120px">

                <el-row class="mt15">
                    <el-col :span="24">
                        <el-form-item label="图件名称" prop="mapName">
                            <el-input style="width: 100%;" v-model="otherForm.mapName" placeholder="请输入图件名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="图件分类" prop="mapClassify">
                            <el-select v-model="otherForm.mapClassify" placeholder="请选择图件分类" style="width: 100%;">
                                <el-option v-for="item in [{ value: '0', label: '基础数据' }, { value: '1', label: '评估结果' }]"
                                    :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="任务名称" prop="taskName">
                            <el-select v-model="otherForm.taskName" filterable @change="chooseTaskName"
                                placeholder="请输入所属任务" style="width: 100%;">
                                <el-option v-for="(item, index) in taskList" :key="item.id"
                                    :label="item.taskCodeAndTaskName" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row>
                    <el-col :span="8">
                        <el-form-item label="省" prop="provinceId">
                            <el-select v-model="otherForm.provinceId" placeholder="请输入省" @change="chooseFormProvince"
                                style="width: 100%;">
                                <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="cityId">
                            <el-select v-model="otherForm.cityId" placeholder="请输入市" @change="chooseFormCity"
                                style="width: 100%;">
                                <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区/县" prop="areaId">
                            <el-select v-model="otherForm.areaId" placeholder="请输入区/县" @change="chooseFormArea"
                                style="width: 100%;">
                                <el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="图片" prop="picture">
                            <image-upload ref="otherImgUpload" :fileSize="100" :limit="1" v-model="otherForm.attachList" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="图件描述" prop="mapDescription">
                            <el-input v-model="otherForm.mapDescription" type="textarea" :disabled="btnType == 'check'"
                                maxlength="1000" show-word-limit :autosize="{ minRows: 4, maxRows: 5 }"
                                placeholder="请输入图件描述" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button plain @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 一键出图 -->
        <el-dialog title="一键出图" v-model="chartShow" width="900px" append-to-body @open="closeChart" @close="closeChart"
            :close-on-click-modal="false">
            <el-form :model="chartForm" ref="chartFormRef" :inline="true" :rules="chartFormRules" class="chartForm"
                label-width="120px" v-loading="chartLoading">
                <el-form-item label="报告类型" prop="reportType">
                    <el-radio-group v-model="chartForm.reportType" class="ml-4" @change="getTable">
                        <el-radio label="0">预评估报告</el-radio>
                        <el-radio label="1">现场调查报告</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label=" " prop="format">
                    <el-radio-group v-model="chartForm.format" class="ml-4" @change="formatChange">
                        <el-radio label="0">横版</el-radio>
                        <el-radio label="1">竖版</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="选择任务" prop="taskName">
                    <el-select v-if="chartForm.reportType==1" v-model="chartForm.taskName" filterable clearable @change="taskNameChanges">
                        <el-option v-for="(item, index) in taskNameOption" :key="item.id" :label="item.taskCodeAndTaskName"   :value="item.id"></el-option>
                    </el-select>
                    <el-select v-if="chartForm.reportType==0" v-model="chartForm.taskName" filterable clearable @change="taskNameChange" style="width: 100%;">
                        <el-option v-for="(item, index) in taskList" :key="item.id" :label="item.taskCodeAndTaskName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="制图单位" prop="unit">
                    <el-input v-model="chartForm.unit" clearable></el-input>
                </el-form-item>
                <el-row style="margin: 10px 0">
                    <el-button plain >
                        <el-checkbox v-model="checkAll" @change="handleCheckAllChange">
                            全选
                        </el-checkbox>
                    </el-button>
                </el-row>
                <el-row>
                    <el-col :span="12" class="borderItem">
                        <el-row>
                            <el-col :span="3" class="checkboxTd"></el-col>
                            <el-col :span="9" class="mapTypeTd">图件类型名称</el-col>
                            <el-col :span="12" class="templateTd">图件模板</el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="12" class="borderItem">
                        <el-row>
                            <el-col :span="3" class="checkboxTd"></el-col>
                            <el-col :span="9" class="mapTypeTd">图件类型名称</el-col>
                            <el-col :span="12" class="templateTd">图件模板</el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="12" class="borderItem" v-for="item in chartForm.chartTable">
                        <el-row>
                            <el-col :span="3" class="checkboxTd">
                                <el-checkbox-group v-model="chartForm.chartChecked">
                                    <el-checkbox v-if="item.typeId" :label="item.typeId">{{ '' }}</el-checkbox>
                                </el-checkbox-group>
                            </el-col>
                            <el-col :span="9" class="mapTypeTd mapTypeTdContent">{{ item.type }}</el-col>
                            <el-col :span="12" class="templateTd">
                                <el-form-item :prop="item.typeId + '-' + item.tempChecked"
                                    :rules="[{ validator: curTempChecked }]">
                                    <el-select v-if="item.template" placeholder="请选择图件模板" v-model="item.tempChecked"
                                        @change="templateChange(item)" clearable>
                                        <el-option v-for="temp in item.template" :id="temp.templateId"
                                            :label="temp.templateName" :value="temp.format" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="test">一键出图</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="ChartManger">
import { getFuTask, queryMaps, saveMap, getById, downLoadFile, update, deleteByIds, getByLabel, getChartTempTable, getTask, supergraph } from "@/api/resultManag/chartManger";
import { getProvince, getChildArea } from "@/api/system/division";
import { reactive } from "vue";
import { saveAs } from 'file-saver'
import { ElMessageBox, ElLoading } from 'element-plus'

const { proxy } = getCurrentInstance();


const dataList = ref([]);
const btnType = ref('add')
const reportShowPopup = ref(false);  //简本报告图件弹窗
const otherShowPopup = ref(false);  //其他图件弹窗
const reportTitle = ref("");//弹窗标题
const otherTitle = ref("");//弹窗标题
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const uploadDisabled = ref(false);

const uploadTime = ref("");//提交时间
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const taskList = ref([])

const data1 = reactive({
    reportForm: {},
    queryParams: {
        page: 1,
        rows: 10,
        taskName: null,
        provinceId: null,
        province: null,
        cityId: null,
        city: null,
        areaId: null,
        area: null,
        uploader: null,
        // uploadTime: null,
        startTime: null,
        endTime: null,
    },
    reportRules: {
        taskName: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
        mapClassify: [{ required: true, message: "图件分类不能为空", trigger: "blur" }],
        mapName: [{ required: true, message: "图件名称不能为空", trigger: "blur" }],
        mapLabel: [{ required: true, message: "图件标签不能为空", trigger: "blur" }],
        mapDescription: [{ required: true, message: "图件描述不能为空", trigger: "blur" }],
        picture: [{ required: true, message: "图件不能为空", trigger: "blur", validator: validatorImg }]
    }
});
const data2 = reactive({
    otherForm: {

    },
    otherRules: {
        mapClassify: [{ required: true, message: "图件分类不能为空", trigger: "blur" }],
        mapName: [{ required: true, message: "图件名称不能为空", trigger: "blur" }],
        mapDescription: [{ required: true, message: "图件描述不能为空", trigger: "blur" }],
        provinceId: [{ required: true, message: '请选择省', trigger: 'blur' }],
        cityId: [{ required: true, message: '请选择市', trigger: 'blur' }],
        areaId: [{ required: true, message: '请选择区/县', trigger: 'blur' }],
        picture: [{ required: true, message: "图件不能为空", trigger: "blur", validator: validatorImg }],
    }
});

const { queryParams, reportForm, reportRules } = toRefs(data1);
const { otherForm, otherRules } = toRefs(data2);

function imgSuccess(response, file, fileList) {
    uploadDisabled.value = true;
}

//自定义图片上传验证
function validatorImg(rule, value, callback) {
    let refName = reportShowPopup.value == true ? 'reportImgUpload' : 'otherImgUpload'
    if (proxy.$refs[refName].fileList.length > 0) {
        callback();
    } else {
        callback(new Error('图件不能为空'));
    }
}

/** 查询列表 */
function getList() {
    loading.value = true;
    queryMaps(queryParams.value).then(response => {
        dataList.value = response.data.rows;;
        total.value = response.data.total;
        loading.value = false;
    });
    getFuTask().then(response => {
        taskList.value = response.data;
    })
}

/** 获取省列表 */
function getProvinceData() {
    getProvince().then(response => {
        provinceData.value = response.data;
    });
}

function getProvinceFormData() {
    getProvince().then(response => {
        provinceFormData.value = response.data;
    });
}

function chooseProvince(value) {
    queryParams.value.cityId = null;
    queryParams.value.areaId = null;
    queryParams.value.city = null;
    queryParams.value.area = null;
    cityData.value = [];
    areaData.value = [];
    getChildArea(value).then(response => {
        cityData.value = response.data;
    });
    queryParams.value.province = provinceData.value.find(item => item.id == value)?.name;
}

function chooseArea(value) {
    queryParams.value.area = areaData.value.find(item => item.id == value)?.name;
}

function chooseCity(value) {
    queryParams.value.area = null;
    queryParams.value.areaId = null;
    areaData.value = [];
    getChildArea(value).then(response => {
        areaData.value = response.data;
    });
    queryParams.value.city = cityData.value.find(item => item.id == value)?.name
}

function chooseFormProvince(value) {
    otherForm.value.city = null;
    otherForm.value.area = null;
    otherForm.value.cityId = null;
    otherForm.value.areaId = null;
    cityFormData.value = [];
    areaFormData.value = [];
    getChildArea(value).then(response => {
        cityFormData.value = response.data;
    });
    otherForm.value.province = provinceFormData.value.find(item => item.id == value)?.name;
}

function chooseFormCity(value) {
    otherForm.value.area = null;
    otherForm.value.areaId = null;
    areaFormData.value = [];
    getChildArea(value).then(response => {
        areaFormData.value = response.data;
    });
    otherForm.value.city = cityFormData.value.find(item => item.id == value)?.name;
}

function chooseFormArea(value) {
    otherForm.value.area = areaFormData.value.find(item => item.id == value)?.name;
}

//选择任务处理数据
function chooseTaskName(value) {
    taskList.value.map(item => {//遍历数据
        if (item.id == value) {
            if (otherShowPopup.value === true) {
                otherForm.value.taskId = item.id;
                otherForm.value.taskName = item.taskCodeAndTaskName;
                otherForm.value.taskDistrict = item.taskDistrict;
                return;
            }
            reportForm.value.taskId = item.id;
            reportForm.value.taskName = item.taskCodeAndTaskName;
            reportForm.value.taskDistrict = item.taskDistrict;
            return;
        }
    })
}

//下载图件
function uploadImg() {
    // saveAs(reportForm.value.attachList[0].url, '图件')
  let attachList = reportForm.value.attachList;
  for(let i=0;i<attachList.length;i++){
    saveAs(attachList[i].url, '图件')
  }
}

// 取消按钮
function cancel() {
    reportShowPopup.value = false;
    otherShowPopup.value = false;
    reset();
}

// 表单重置
function reset() {
    reportForm.value = {};
    otherForm.value = {};
    proxy.resetForm("reportRef");
    proxy.resetForm("otherRef");
    reportForm.value.attachList = [];
    otherForm.value.attachList = [];
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    queryParams.value.startTime = uploadTime.value ? uploadTime.value[0] + ' 00:00:00' : "";
    queryParams.value.endTime = uploadTime.value ? uploadTime.value[1] + ' 23:59:59' : "";
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    uploadTime.value = [];
    cityData.value = [];
    areaData.value = [];
    // queryParams.value = {};
    queryParams.value.province = null;
    queryParams.value.city = null;
    queryParams.value.area = null;
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
    uploadTime.value = null;
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.mapId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function reportHandleAdd() {
    reset();
    reportShowPopup.value = true;
    reportTitle.value = "按简本报告上传图件";
    btnType.value = 'add'
}

/** 新增按钮操作 */
function otherHandleAdd() {
    reset();
    otherShowPopup.value = true;
    otherTitle.value = "其他图件上传";
    getProvinceFormData();
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const id = row.mapId || "";
    btnType.value = 'edit';
    getById(id).then(response => {
        reportForm.value = response.data.mapManagementEntity;
        reportForm.value.attachList = [];
        // let attach = response.data.attach || [];
        // reportForm.value.attachList.push({ attachId: attach.attachId || '', name: attach.attachName || '', url: import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(attach.attachId) || '' });
        let attachList = response.data.attachList || [];
        for(let i=0;i<attachList.length;i++){
          let attach = attachList[i];
          reportForm.value.attachList.push({ attachId: attach.attachId || '', name: attach.attachName || '', url: import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(attach.attachId) || '' });
        }
        reportForm.value.id = response.data.mapManagementEntity.mapId;
        reportShowPopup.value = true;
        reportTitle.value = "修改图件信息";

    });
}

/** 提交按钮 */
function submitForm() {
    let refName = "reportRef";
    let form = reportForm.value;
    let fileList = [];
    if (otherShowPopup.value === true) {
        refName = "otherRef";
        form = otherForm.value;
        fileList = proxy.$refs["otherImgUpload"].fileList;
        if (fileList.length) otherForm.value.attachId = fileList[0].attachId || "";
    }
    else {
        fileList = proxy.$refs["reportImgUpload"].fileList;
        if (fileList.length) reportForm.value.attachId = fileList[0].attachId || "";
    }
    proxy.$refs[refName].validate(valid => {
        if (valid) {
            if (reportShowPopup && reportForm.value.id != null) {
                update(reportForm.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    reportShowPopup.value = false;
                    otherShowPopup.value = false;
                    getList();
                });
            } else {
                if (reportShowPopup.value == true) {
                    getByLabel({ taskId: form.taskId, mapLabel: form.mapLabel }).then(response => {
                        if (response.data !== null) {
                            return proxy.$modal.confirm("该任务相同标签下已有图片,重复上传将会覆盖，是否继续").then(function () {
                                return save();

                            })
                        }
                        return save();
                    })
                } else {
                    save();
                }

                function save() {
                    saveMap(form).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        reportShowPopup.value = false;
                        otherShowPopup.value = false;
                        getList();
                    });
                }

            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete() {
    if (!ids.value.length) {
        return proxy.$modal.msgWarning("请选择要删除的数据");
    }
    proxy.$modal.confirm('是否确认删除选中的数据项？').then(function () {
        return deleteByIds(ids.value);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

// 一键出图
const chartData = reactive({
    chartShow: false,
    chartLoading: false,
    chartForm: {
        reportType: '0',
        format: '',
        taskName: '',
        unit: '',
        chartChecked: [],
        chartTable: []
    },
    taskNameOption: []
})
const { chartShow, chartLoading, chartForm, taskNameOption } = toRefs(chartData)
const chartFormRules = reactive({
    reportType: [{ required: true, message: '请选择报告类型！', trigger: 'change' }],
    taskName: [{ required: true, message: '请选择任务！', trigger: 'change' }],
    unit: [{ required: true, message: '请填写制图单位！', trigger: 'blur' }],
    chartChecked: [{ required: true, message: '请选择图件类型！', trigger: 'change' }]
})
// 打开一键出图
const chartHandle = () => {
    chartShow.value = true
    getTable()
}
// 全选
const checkAll = ref(false)
const handleCheckAllChange = (val) => {
    if (val) {
        chartForm.value.chartChecked = chartForm.value.chartTable.map(item => item.typeId)
    } else {
        chartForm.value.chartChecked = []
    }
}
// 获取表格数据
const getTable = () => {
    chartLoading.value = true
    // 获取一键出图表格数据时，判断单数则+1
    getChartTempTable(chartForm.value.reportType).then(res => {
      if (res.code == 200) {
        // chartLoading.value = false
        chartForm.value.chartTable = res.data
        if (chartForm.value.chartTable.length % 2 == 1) {
          chartForm.value.chartTable.push({})
        }
      }
    })
    //根据类型获取任务列表
    getTask(chartForm.value.reportType).then(res => {
      if (res.code == 200){
        taskNameOption.value = res.data
      }
      //防止切换类型获取任务列表错误
      chartLoading.value = false
      console.log(taskNameOption.value)
    })
    chartForm.value.taskName = ''
    chartForm.value.format = ''
}
// 关闭
const closeChart = () => {
    proxy.resetForm('chartFormRef')
    chartForm.value.chartChecked = []
}
const preVo = ref({})
const taskNameChange = (val) => {
    let selectItem = taskList.value.find(item => item.id == val)
    const { id, taskDistrict, taskCodeAndTaskName } = selectItem
    preVo.value = { id, taskDistrict, taskCodeAndTaskName }
    // let selectItem = taskNameOption.value.find(item => item.id == val)
    // const {id, taskDistrict, taskCodeAndTaskName} = selectItem 
    // preVo.value = {id, taskDistrict, taskCodeAndTaskName}
}
const taskNameChanges = (val) => {
    let selectItem = taskNameOption.value.find(item => item.id == val)
    const { id, taskDistrict, taskCodeAndTaskName } = selectItem
    preVo.value = { id, taskDistrict, taskCodeAndTaskName }
    // let selectItem = taskNameOption.value.find(item => item.id == val)
    // const {id, taskDistrict, taskCodeAndTaskName} = selectItem 
    // preVo.value = {id, taskDistrict, taskCodeAndTaskName}
}

// 版式选择
const formatChange = (val) => {
    chartForm.value.chartTable = chartForm.value.chartTable.map(item => {
        if (!item.typeId) return item
        item.tempChecked = ''
        item.templateId = item.template.find(itemTemp => itemTemp.format == val)?.templateId
        if (item.templateId) item.tempChecked = val
        return item
    })
}
// 图件模板切换
const templateChange = (val) => {
    val.templateId = val.template.find(item => item.format == val.tempChecked)?.templateId
}
// 校验模板是否选择
const curTempChecked = (rule, value, callback) => {
    if (chartForm.value.chartChecked.includes(rule.field.split('-')[0])) {
        if (rule.field.split('-')[1] == '' || rule.field.split('-')[1] == 'undefined') {
            callback(new Error('请选择图件模板！'))
        } else {
            callback()
        }
    }
    callback()
}
// 一键出图
const test = () => {
    proxy.$refs['chartFormRef'].validate((valid, fields) => {
        if (valid) {
            let chartTable = chartForm.value.chartChecked
            if (chartTable.length == 0) {
                proxy.$modal.msgError('请选择图件类型及模板!')
                return
            }

            let newChartTable = []
            chartTable.map(item => {
                newChartTable = [...newChartTable, ...chartForm.value.chartTable.filter(itemTemp => {
                    if (item == itemTemp.typeId) return itemTemp
                })]
            })
            let mapTemplates = newChartTable.map(item => {
                return item.template.find(TempItem => {
                    return TempItem.format == item.tempChecked
                })
            })

            const { reportType, unit } = chartForm.value
            let data = { reportType, unit, preVo: preVo.value, mapTemplates }
            ElMessageBox.confirm(`所选任务如已生成相应图件将被覆盖，请确认是否继续。`, "系统提示", {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: "warning",
                cancelButtonClass: 'is-plain',
            }).then(() => {
                const chartFormLoading = ElLoading.service({
                    lock: true,
                    text: '一键出图中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                })
                supergraph(data).then(res => {
                    if (res.code == 200 && res.data) {
                        // proxy.$modal.msgSuccess('一键出图成功！')
                        proxy.$modal.alertSuccess('一键出图成功！')
                        chartShow.value = false
                        queryParams.value.page = 1
                        getList()
                    } else {
                        // res.message && proxy.$modal.msgWarning(res.message)
                        res.message && proxy.$modal.alertError(res.message);
                    }
                    chartFormLoading.close()
                }).catch(err => chartFormLoading.close())
            }).catch(() => { })
        } else {
            proxy.$refs['chartFormRef'].scrollToField(Object.keys(fields)[0])
        }
    })
}

getList();
getProvinceData();
</script>

<style lang="scss" scoped>
.mt15 {
    margin-top: 15px;
}

.disabled .el-upload--picture-card {
    display: none;
}
</style>
<style lang="scss">
.el-table.chartTable {
    td.el-table__cell {
        border-right: var(--el-table-border) !important;
        border-bottom: var(--el-table-border) !important;
    }

    .el-table__header-wrapper th {
        background-color: #fff !important;
    }
}

.chartForm {
    .borderItem {
        width: 50%;
        border: 1px solid #ebeef5;
        border-bottom: none;
        margin: 0;
        display: inline-block;

        &:nth-child(2n) {
            border-left: none;
        }

        &>.el-row {
            height: 100%;
        }

        .checkboxTd,
        .mapTypeTd,
        .templateTd {
            padding: 15px 10px;
            min-height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .mapTypeTdContent {
            justify-content: start;
        }

        .checkboxTd,
        .mapTypeTd {
            border-right: 1px solid #ebeef5;
        }

        .templateTd {
            .el-form-item {
                margin: 0;
            }
        }
    }

    .borderItem:last-child,
    .borderItem:nth-last-child(2) {
        border-bottom: 1px solid #ebeef5;
    }
}
</style>
